package com.xhx.accounting;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Objects;

public class add_plan extends AppCompatActivity {
    private DBDao db;
    private Calendar calendar;
    private TextView listDatePicker1;
    private TextView listDatePicker2;
    private EditText listNameInput;
    private EditText listGoalInput;
    private String listName;
    private String listGoal;
    private long timeStamp1;
    private long timeStamp2;
    private Button add_button;
    private SQLiteDatabase mDatabase;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = new DBDao(add_plan.this);
        setContentView(R.layout.activity_add_plan);
        calendar = Calendar.getInstance();
        listDatePicker1 = findViewById(R.id.write_start_time);
        listDatePicker2 = findViewById(R.id.write_deadline);
        listNameInput = findViewById(R.id.write_name);
        listGoalInput = findViewById(R.id.write_goal);
//        listNameInput.setFocusable(true);
//        listGoalInput.setFocusable(true);
//        listNameInput.setFocusableInTouchMode(true);
//        listGoalInput.setFocusableInTouchMode(true);
        listNameInput.requestFocus();

        listDatePicker1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(add_plan.this, 0);
            }
        });

        listDatePicker2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog1(add_plan.this, 0);
            }
        });

        add_button = findViewById(R.id.add_button);
        add_button.setOnClickListener(v -> {
            listName = listNameInput.getText().toString().trim();
            listGoal = listGoalInput.getText().toString().trim();
            String startTime = Long.toString(timeStamp1);
            String deadline = Long.toString(timeStamp2);
            if (listName.length()!=0 && listGoal.length()!=0 && String.valueOf(timeStamp1).length()!=0 && String.valueOf(timeStamp2).length()!=0) {
                db.addPlan(listName,startTime,deadline,listGoal);
                Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                finish();
            }else{
                Toast.makeText(this, "请填写完整", Toast.LENGTH_SHORT).show();
            }
        });

    }
  
    public void showDatePickerDialog(Context context, int themeResId) {
        new DatePickerDialog(context, themeResId, (view, year, month, dayOfMonth) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.set(year, month, dayOfMonth);
            String listDate = sdf.format(calendar.getTime());
            try {
                timeStamp1 = Objects.requireNonNull(sdf.parse(listDate)).getTime() / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            listDatePicker1.setText(listDate);
            Log.d("DateStamp", String.valueOf(timeStamp1));
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    public void showDatePickerDialog1(Context context, int themeResId) {
        new DatePickerDialog(context, themeResId, (view, year, month, dayOfMonth) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.set(year, month, dayOfMonth);
            String listDate = sdf.format(calendar.getTime());
            try {
                timeStamp2 = Objects.requireNonNull(sdf.parse(listDate)).getTime() / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            listDatePicker2.setText(listDate);
            Log.d("DateStamp", String.valueOf(timeStamp2));
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.arrow_left:
                finish();
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /*
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /*
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}